﻿using Arch.EntityFrameworkCore.UnitOfWork;
using AutoMapper;
using MyTodoApi.Context;
using Shared.ToDo.Dtos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyTodoApi.Services
{
    public class ToDoService : BaseService<ToDoDto, ToDo>, IToDoService
    {
        private readonly IUnitOfWork unitOfWork;
        private readonly IMapper mapper;

        public ToDoService(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper)
        {
            this.unitOfWork = unitOfWork;
            this.mapper = mapper;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="toDo"></param>
        /// <returns></returns>
        new public async Task<ApiResponse> UpdateAsync(ToDoDto toDodto)
        {
            try
            {
                var todo = mapper.Map<ToDo>(toDodto);
                var repository = unitOfWork.GetRepository<ToDo>();
                var todoEntity = await repository.GetFirstOrDefaultAsync(predicate: x => x.ID.Equals(todo.ID));
                if (todoEntity != null)
                {
                    todoEntity.Titile = todo.Titile;
                    todoEntity.Description = todo.Description;
                    todoEntity.Status = todo.Status;
                    todoEntity.UpdateTime = DateTime.Now;
                }
                repository.Update(todoEntity);
                var result = await unitOfWork.SaveChangesAsync();
                if (result > 0)
                {
                    return new ApiResponse(true, todoEntity);
                }
                else
                {
                    return new ApiResponse(false, "保存失败");
                }
            }
            catch (Exception ex)
            {
                return new ApiResponse(false, ex.Message);
            }
        }
    }
}
